import axios from 'axios';
import qs from "qs";
import {
	ElMessage,
	ElLoading
} from 'element-plus';
import storage from "@/utils/storage";

// 创建axios实例
const _axios = axios.create({
	// baseURL: import.meta.env.VITE_APP_BASE_API, //服务接口请求
	timeout: 10000, //超时设置
})

let loading = null;
// 显示loading
const showLoading = (loadingText) => {
	loading = ElLoading.service({
		text: loadingText || "请求中...",
		background: "rgba(0, 0, 0, 0)",
		// spinner: "el-icon-loading",
	});
}

// 隐藏loading
const hideLoading = () => {
	if (loading) {
		loading.close()
	}
}

// 请求拦截
_axios.interceptors.request.use(config => {
	// console.log('请求拦截', config);
	return config
}, error => {
	// console.log('请求拦截error', error)
	return Promise.reject(error)
})

// 响应拦截器
const errorQueue = []
let errorCount = 0;
_axios.interceptors.response.use((res) => {
		console.log('请求结果', res)
		setTimeout(() => {
			hideLoading();
		}, 500)
		if (res.data.code === 'USER_NOT_LOGIN') {
			// 未登录 or token过期
			ElMessage.error(res.data.info)
			errorCount = 1
			setTimeout(() => {
				errorCount = 0
			}, 5000)
			location.href = "#/login";
		} else if (res.data.sucess) {
			return Promise.resolve(res.data.data)
		} else {
			return Promise.resolve(res)
			/*if (res.data.info.includes('用户[')) {
				ElMessage.error('账号或密码错误')
			} else {
				ElMessage.error(res.data.info)
			}
			errorCount = 1
			setTimeout(() => {
				errorCount = 0
			}, 5000)
			return Promise.reject(res)*/
		}
	},
	error => {
		console.log('接口请求失败', error)
		setTimeout(() => {
			hideLoading();
		}, 500)
		let {
			message
		} = error;
		if (error.response && error.response.data.code === 'USER_NOT_LOGIN') {
			// 未登录 or token过期
			ElMessage.error(error.response.data.info)
			errorCount = 1
			setTimeout(() => {
				errorCount = 0
			}, 5000)
			location.href = "#/login";
		} else if (message == "Network Error") {
			message = "后端接口连接异常";
		} else if (message.includes("timeout")) {
			message = "网络请求超时，请稍后再试";
		} else if (message.includes("Request failed with status code")) {
			message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		if (errorCount === 0) {
			ElMessage.error({
				message: message,
				duration: 5 * 1000
			})
			errorCount = 1
			setTimeout(() => {
				errorCount = 0
			}, 5000)
		}
		return Promise.reject(error)
	}
)

const _http = (opt) => {
	// console.log('传递的参数', opt);
	if (opt.isLoading) {
		showLoading(opt.loadingText);
	}
	let options = opt.data;
	_axios.defaults.headers.common['Authorization'] = storage.SStorage.get('authorization');
	let tempParams;
	if (opt.isBlob) {
		_axios.defaults.responseType = 'blob';
	} else {
		_axios.defaults.responseType = 'json';
	}
	if (opt.isBody) {
		_axios.defaults.headers.post["Content-Type"] = "application/json";
		_axios.defaults.headers.put["Content-Type"] = "application/json";
		_axios.defaults.headers.delete["Content-Type"] = "application/json";
		tempParams = options;
	} else {
		_axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
		tempParams = qs.stringify(options);
	}
	return new Promise((resolve, reject) => {
		if (opt.type == "post") {
			_axios.post(opt.url, tempParams).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		} else if (opt.type == "get") {
			_axios.get(opt.url, {
				params: options
			}).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		} else if (opt.type == "put") {
			_axios.put(opt.url, tempParams).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		} else if (opt.type == "delete") {
			_axios.delete(opt.url, {
				params: options
			}).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		}
	})
}

export default _http;